package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"order/api/request"
	"order/inter/dao"
	"order/inter/model"
)

func CreatePro(c *gin.Context) {
	var req request.CreatePro
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var pro model.Products
	dao.GetOneByFields(&model.Products{Title: req.Title}, &pro)
	if pro.Id != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "此账号已存在",
			"data": nil,
		})
		return
	}
	pro = model.Products{
		Title:  req.Title,
		Common: req.Common,
	}
	if !dao.Create(&pro) {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "商品添加失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": pro,
	})
}

func FindPro(c *gin.Context) {
	var pro []model.Products
	dao.GetListByFields(&model.Products{}, &pro)

	var pros []*model.Products
	for _, v := range pro {
		pros = append(pros, &v)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": pros,
	})
}

func UpdatePro(c *gin.Context) {
	var req request.UpdatePro
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 1000,
		"msg":  "验证失败",
		"data": dao.Update(&model.Products{
			Id:     uint64(req.Id),
			Title:  req.Title,
			Common: req.Common,
		}),
	})
}

func DelPro(c *gin.Context) {
	var req request.DelPro
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 1000,
		"msg":  "验证失败",
		"data": dao.Delete(&model.Products{
			Id: uint64(req.Id),
		}),
	})
}
